package com.itheima.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author ghy
 * @version 1.0
 * @date 2022-10-18 11:21
 */
@Component
@Aspect
public class GetDataAdvice {
    @Pointcut("ExecutionEfficiencyAdvice.testSpeed()")
    public void testSpeed(){}


    //定义切入点
    @Pointcut("execution(* com.itheima.service.impl.AccountServiceImpl.*(..))")
    public void pt(){}

    public void before(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        if(args != null && args.length > 0) {
            System.out.println("参数: " + Arrays.asList(args));
        }else {
            System.out.println("参数: []");
        }

        //获取目标所在的类对象
        String className = joinPoint.getSignature().getDeclaringTypeName();

        //获取目标方法名称
        String methodName = joinPoint.getSignature().getName();
        System.out.println(className +"."+ methodName + "正在执行---->");
    }
    
    
    @AfterReturning(value = "pt()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        System.out.println("返回通知" + result);
    }

    @AfterThrowing(value = "pt()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex){
        System.out.println("异常通知" + ex);
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object result = null;
        try {
            Object[] args = pjp.getArgs();
            if(args != null && args.length > 0) {
                System.out.println("参数: " + Arrays.asList(args));
            }else {
                System.out.println("参数: []");
            }
            //获取目标所在的类对象
            String className = pjp.getSignature().getDeclaringTypeName();

            //获取目标方法名称
            String methodName = pjp.getSignature().getName();
            System.out.println(className +"."+ methodName + "正在执行---->");
            result = pjp.proceed();
            System.out.println("返回值" + result);
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("返回值异常" + e);
        }finally {
            System.out.println("后置通知干的活  ~~~~");
        }
        return result;
    }
}
